<template>
  <div class="content">
    <div class="flex flex-justify-between questionContent">
      <div class="question_content w60">
        <!-- <div class="expand flex flex-align-center flex-justify-center cursor_pointer"
          @click="if_analysis = !if_analysis" :class="{ expanded: if_analysis }">
          <img src="@/assets/img/analysis.png" alt="" class="analysisIcon" v-if="if_analysis == false">
          <div v-if="if_analysis == false">解析</div>
          <div v-else class="flex flex-align-center">
            <el-icon>
              <DArrowRight />
            </el-icon>
            <div>收起</div>
          </div>
        </div> -->
        <div class="flex" v-if="currentQuestion">
          <div class="questionType" v-if="currentQuestion.type < 3">
            {{
              currentQuestion.type == '1' ? '单选' : currentQuestion.type == '2' ? '判断' : '多选'
            }}
          </div>
          <!-- <div class="rules marL10" v-if="currentQuestion.newTg == 1">新题规</div> -->
          <div class="marL10 title">{{ currentQuestion.title }}</div>
        </div>
        <div class="flex">
          <div style="width: 40%;">
            <div v-for="(item, i) in currentQuestion?.options || []" :key="i">
              <div class="flex marT50 cursor_pointer" @click="optionFun(i, item.option)" v-if="item.name">
                <div class="w90 flex flex-align-center flex-justify-center">
                  <!-- 多选（type=='0'） -->
                  <template v-if="currentQuestion.type == '0'">
                    <!-- 已确认：错误优先显示红叉，正确显示对勾，其余显示字母 -->
                    <template v-if="hasConfirmed">
                      <div class="option-false" v-if="wrongSelectedOptions.includes(item.option)">
                        <el-icon>
                          <CloseBold />
                        </el-icon>
                      </div>
                      <div class="option-true"
                        v-else-if="currentQuestion.answer.includes(item.option) && selectedOptions.includes(item.option)">
                        <el-icon><Select /></el-icon>
                      </div>
                      <div class="option-num option-true"
                        v-else-if="currentQuestion.answer.includes(item.option) && !selectedOptions.includes(item.option)">
                        {{ item.option }}
                      </div>
                      <div class="option-num" v-else>{{ item.option }}</div>
                    </template>
                    <!-- 未确认：仅已选中显示对勾，未选显示字母 -->
                    <template v-else>
                      <div class="option-true" v-if="selectedOptions.includes(item.option)">
                        <el-icon><Select /></el-icon>
                      </div>
                      <div class="option-num" v-else>{{ item.option }}</div>
                    </template>
                  </template>
                  <!-- 单选/判断：原逻辑 -->
                  <template v-else>
                    <div class="option-true"
                      v-if="optionTab == i && currentQuestion.answer == currentQuestion.answered">
                      <el-icon><Select /></el-icon>
                    </div>
                    <div class="option-false"
                      v-else-if="optionTab == i && currentQuestion.answer != currentQuestion.answered">
                      <el-icon>
                        <CloseBold />
                      </el-icon>
                    </div>
                    <div class="option-num" v-else>{{ item.option }}</div>
                  </template>
                </div>

                <div class="marL10 f28" :class="currentQuestion.type == '0'
                  ? (hasConfirmed
                    ? (wrongSelectedOptions.includes(item.option)
                      ? 'errorFont'
                      : (currentQuestion.answer.includes(item.option) ? 'successFont' : ''))
                    : (selectedOptions.includes(item.option) ? 'successFont' : ''))
                  : (optionTab == i
                    ? currentQuestion.answer == currentQuestion.answered
                      ? 'successFont'
                      : 'errorFont'
                    : '')
                  ">
                  {{ item.name }}
                </div>
              </div>
            </div>
            <div class="unmultiple" v-if="currentQuestion && currentQuestion.type == '0' && !hasConfirmed"
              @click="confirmMultipleChoice" :class="{ 'multipled': selectedOptions.length > 0 }">
              确认
            </div>
          </div>
          <div v-if="currentQuestion && currentQuestion.img && if_analysis" class="tipsImgs">
            <el-image :src="currentQuestion.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
              :preview-src-list="[currentQuestion.img]" show-progress :initial-index="4" fit="cover"
              :hide-on-click-modal="true" />
            <p>点击图片查看大图</p>
          </div>
        </div>
      </div>
      <div v-if="currentQuestion && currentQuestion.img && !if_analysis" class="tipsImg" style="width: 40%;">
        <el-image :src="currentQuestion.img" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
          :preview-src-list="[currentQuestion.img]" show-progress :initial-index="4" fit="cover"
          :hide-on-click-modal="true" />
        <p>点击图片查看大图</p>
      </div>
      <!-- 解析 -->
      <div class="analysis" v-if="if_analysis == true">
        <div class="back-to-top flex flex-align-center flex-justify-center" v-show="showBackToTop" @click="scrollToTop">
          <el-icon size="30">
            <Top />
          </el-icon>
        </div>
        <div class="analysis_content">
          <div class="analysis_header">
            <div class="correct_answer flex flex-align-center flex-justify-between">
              <div>
                <span class="answer_title">正确答案：</span>
                <span class="answer_option">{{ currentQuestion.answer }}</span>
              </div>
              <!-- <div class="correction">纠错</div> -->
            </div>
          </div>
          <div class="gap"></div>
          <div class="suji">
            <div class="flex flex-align-center">
              <div class="line"></div>
              <div class="marL10 analysis_title">速记口诀</div>
            </div>
            <div class="cont">
              <!-- <p>秒懂技巧: {{ currentQuestion.fastStudy }}</p> -->
              <p>{{ currentQuestion.fastStudy }}</p>
              <!-- <div class="bg"></div>
              <div class="check">查看完整技巧</div> -->
            </div>
          </div>
          <div class="gap"></div>
          <div class="suji">
            <div class="flex flex-align-center">
              <div class="line"></div>
              <div class="marL10 analysis_title">题目解析</div>
            </div>
            <div class="analysis_item">
              {{ currentQuestion.questionAnalysis }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部题库 -->
    <div class="question_bank">
      <div class="flex flex-align-center flex-justify-between use">
        <div class="flex flex-align-center">
          <div class="cursor_pointer" @click="previousQuestion"
            :class="currentQuestionIndex == 0 ? 'boundary_button' : 'default_button'">
            上一题
          </div>
          <div class="marL40 cursor_pointer" @click="nextQuestion" :class="currentQuestionIndex == optionList.length - 1 ? 'boundary_button' : 'default_button'
            ">
            下一题
          </div>
          <div class="flex flex-align-center marL80 cursor_pointer" @click="questionDrawer = !questionDrawer">
            <div class="true_icon">
              <el-icon><Select /></el-icon>
            </div>
            <div class="marL15 f30">{{ correct }}</div>
            <div class="false_icon marL40">
              <el-icon>
                <CloseBold />
              </el-icon>
            </div>
            <div class="marL15 f30">{{ wrongNum }}</div>
            <img src="../../assets/img/num.jpg" alt="" class="pic35 marL40" />
            <div class="f30 marL15">
              {{ (currentQuestionIndex ?? 0) + 1 }}/{{ optionList.length }}
            </div>
          </div>
        </div>
        <div class="flex">
          <div class="marR20">
            <div class="button flex flex-align-center flex-justify-center cursor_pointer" @click="submitModel = true">
              <img src="@/assets/img/jiaojuan.png" alt="" class="iconImg">
              <div>提前交卷</div>
            </div>
            <div class="flex flex-align-center marT30">
              <div class="f30 flex flex-align-center cursor_pointer" @click="readQuestion">
                <img :src="isplay ? read : unread" alt="" class="iconImg">
                <div class="marL10" :class="isplay ? 'reading' : ''">读题</div>
              </div>
              <!-- @click="currentQuestion.isCollected = !currentQuestion.isCollected" -->
              <div class="f30 marL30 flex flex-align-center cursor_pointer" @click="saveQuestionData('1')">
                <el-icon v-if="currentQuestion && !currentQuestion.isCollected">
                  <Star />
                </el-icon>
                <el-icon color="#fed701" size="40" v-else>
                  <StarFilled />
                </el-icon>
                <div class="marL10">
                  {{ currentQuestion && !currentQuestion.isCollected ? '收藏' : '已收藏' }}
                </div>
              </div>
              <div class="f30 flex flex-align-center marL30">
                <img src="@/assets/img/setting.png" alt="" class="iconImg cursor_pointer">
                <div class="marL10">设置</div>
              </div>
            </div>
          </div>
          <div class="downloadInfo flex flex-justify-center flex-align-center marL20">
            <img src="@/assets/img/ewm.png" alt="" class="downloadImg">
            <div class="download">下载手机版</div>
          </div>
        </div>
      </div>
    </div>
    <!-- 题库抽屉 -->
    <el-drawer v-model="questionDrawer" :direction="questionDirection" :before-close="questionClose"
      class="question-drawer" size="37.5rem" :modal="true" :modal-class="'transparent-drawer-overlay'">
      <div class="flex flex-align-center flex-justify-between use">
        <div class="flex flex-align-center">
          <div class="cursor_pointer" @click="previousQuestion"
            :class="currentQuestionIndex == 0 ? 'boundary_button' : 'default_button'">
            上一题
          </div>
          <div class="marL40 cursor_pointer" @click="nextQuestion" :class="currentQuestionIndex == optionList.length - 1 ? 'boundary_button' : 'default_button'
            ">
            下一题
          </div>
          <div class="flex flex-align-center marL80 cursor_pointer" @click="upPull">
            <div class="true_icon">
              <el-icon><Select /></el-icon>
            </div>
            <div class="marL15 f30">{{ correct }}</div>
            <div class="false_icon marL40">
              <el-icon>
                <CloseBold />
              </el-icon>
            </div>
            <div class="marL15 f30">{{ wrongNum }}</div>
            <img src="../../assets/img/num.jpg" alt="" class="pic35 marL40" />
            <div class="f30 marL15">
              {{ (currentQuestionIndex ?? 0) + 1 }}/{{ optionList.length }}
            </div>
          </div>
        </div>
        <div class="flex">
          <div class="marR20">
            <div class="button flex flex-align-center flex-justify-center cursor_pointer" @click="submitModel = true">
              <img src="@/assets/img/jiaojuan.png" alt="" class="iconImg">
              <div>提前交卷</div>
            </div>
            <div class="flex flex-align-center marT30">
              <div class="f30 flex flex-align-center cursor_pointer" @click="readQuestion">
                <img :src="isplay ? read : unread" alt="" class="iconImg">
                <div class="marL10" :class="isplay ? 'reading' : ''">读题</div>
              </div>
              <!-- @click="currentQuestion.isCollected = !currentQuestion.isCollected" -->
              <div class="f30 marL30 flex flex-align-center cursor_pointer" @click="saveQuestionData('1')">
                <el-icon v-if="currentQuestion && !currentQuestion.isCollected">
                  <Star />
                </el-icon>
                <el-icon color="#fed701" size="40" v-else>
                  <StarFilled />
                </el-icon>
                <div class="marL10">
                  {{ currentQuestion && !currentQuestion.isCollected ? '收藏' : '已收藏' }}
                </div>
              </div>
              <div class="f30 flex flex-align-center marL30">
                <img src="@/assets/img/setting.png" alt="" class="iconImg cursor_pointer">
                <div class="marL10">设置</div>
              </div>
            </div>
          </div>
          <div class="downloadInfo flex flex-justify-center flex-align-center marL20">
            <img src="@/assets/img/ewm.png" alt="" class="downloadImg">
            <div class="download">下载手机版</div>
          </div>
        </div>
      </div>
      <div class="tips">
        <div class="flex flex-align-center flex-justify-between">
          <div class="font40">答题卡</div>
          <div class="clearRecord cursor_pointer" @click="clearRecord">清除记录</div>
        </div>
        <div class="list marT20">
          <div class="list_item cursor_pointer" v-for="(item, index) in optionList" :key="index" :class="{
            active: currentQuestionIndex === index,
            success: item.answer == item.answered,
            wrong_bg:
              item.answer != item.answered && item.answered != null && item.answered != '',
          }" @click="gotoQuestion(index)">
            {{ index + 1 }}
          </div>
        </div>
      </div>
    </el-drawer>
    <el-dialog v-model="clearModel" width="35%" :before-close="handleClose" :close-on-click-modal="false"
      :style="{ borderRadius: '10px', paddingBottom: '40px' }">
      <div class="prompt">温馨提示</div>
      <div class="f35">您确定要清空当前做题记录并重新开始吗？</div>
      <template #footer>
        <div class="dialog-footer flex flex-align-center flex-justify-center">
          <div @click="clearModel = false" class="cancel cursor_pointer">取消</div>
          <div @click="confrim" class="sure marL30 cursor_pointer">清空</div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="submitModel" width="35%" :before-close="submitHandleClose" :close-on-click-modal="false"
      :style="{ borderRadius: '10px', paddingBottom: '60px' }" :show-close="examSure ? false : true">
      <div class="prompt" v-if="!examSure">温馨提示</div>
      <div v-else="examSure" class="prompt">考试确认窗口：</div>
      <div class="sureTips" v-if="examSure">考试时间结束，请点击【确认交卷】，将提交考试成绩，结束考试!</div>
      <div class="font20" v-if="!examSure">1: 点击【确认交卷]，将提交考试成绩，结束考试!</div>
      <div class="font20 marB40" v-if="!examSure">2: 点击【继续考试]，将关闭本窗口，继续考试!</div>
      <template #footer>
        <div class="dialog-footer flex flex-align-center flex-justify-center">
          <div @click="submitModel = false" class="cancel cursor_pointer" v-if="!examSure">取消</div>
          <div @click="onSubmitEarly" class="sure marL30 cursor_pointer">{{ !examSure ? '确认' : '确认交卷' }}</div>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="questionModel" width="25%" :style="{ borderRadius: '10px' }" :close-on-click-modal="false"
      :show-close="false">
      <div class="prompt">考试结果</div>
      <div class="exam-result-container">
        <div class="score">{{ totalScore }}
          <span class="fraction">
            分
          </span>
        </div>
        <div class="center comment">
          {{ totalScore < 90 ? ' 很遗憾，考试不合格！' : '恭喜您，考试合格！' }} </div>
            <div class="stats">
              <div class="stat-item">
                <div class="value correct">{{ correct }}</div>
                <div class="value marT10">答对</div>
              </div>
              <div class="stat-item">
                <div class="value wrong">{{ wrongNum }}</div>
                <div class="value marT10">答错</div>
              </div>
              <div class="stat-item">
                <div class="value unanswered">{{ optionList.length - correct - wrongNum }}</div>
                <div class="value marT10">未答</div>
              </div>
              <div class="stat-item">
                <div class="value">
                  {{ Math.floor((totalExamSeconds - totalSeconds) / 60) }}:{{ ((totalExamSeconds - totalSeconds) %
                    60).toString().padStart(2, '0') }}
                </div>
                <div class="value marT10">用时</div>
              </div>
            </div>
            <div class="actions">
              <div class="wrongCheck" @click="viewWrongQuestions">错题查看</div>
              <div class="backList" @click="backToQuestionBank">返回题库</div>
            </div>
        </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, onMounted, onUnmounted, watch } from 'vue'
import type { DrawerProps } from 'element-plus'
import { Select, CloseBold, DArrowRight, Top, Star, StarFilled } from '@element-plus/icons-vue'
import './index.scss'
import { getSimulateQuestion, getQuestionProgress, getSpecialQuestion, updateExamStatus, getSpeechSynthesis } from '@/api/userApi'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/store/user'
import { useRoute, useRouter } from 'vue-router'
import read from '@/assets/img/read.png'
import unread from '@/assets/img/unread.png'

const examSure = ref(false)
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const submitModel = ref(false)
const questionModel = ref(false)
const optionList = ref<Question[]>([])
// 倒计时
const totalExamSeconds = 45 * 60
const totalSeconds = ref(totalExamSeconds)

const wrongList = ref<any>([])
const originalTitle = ref<any>([])

const wrongState = ref() // 判断是否为错题查看

// watch(
//   route,
//   (newVal) => {
//     wrongState.value = newVal.query.wrong
//     // console.log(wrongState.value, "wrongState====");
//     if (wrongState.value) {
//       getWrongList()
//     }
//   },
//   { immediate: true }
// )

const currentQuestion = computed<any>(() => {
  return optionList.value[currentQuestionIndex.value]
})

const currentOriginal = computed<any>(() => {
  return originalTitle.value[currentQuestionIndex.value]
})

const correct = computed(
  () => optionList.value.filter((q) => q.answered && q.answered === q.answer).length,
)
const wrongNum = computed(
  () => optionList.value.filter((q) => q.answered && q.answered !== q.answer).length,
)

const totalScore = computed(() => userStore.categoryId == 1 ? 1 * correct.value : 2 * correct.value)

// 修正为合法的 DrawerProps['direction'] 值，'btt' 表示 bottom to top
const questionDirection = ref<DrawerProps['direction']>('btt')
const currentQuestionIndex = ref()
// 选择题其中哪一项
const optionTab = ref(-1)
const isSelect = ref(false)
// 多选：临时选中项
const selectedOptions = ref<string[]>([])
// 多选：确认后标记为错误的已选项
const wrongSelectedOptions = ref<string[]>([])
// 多选：本题是否已确认（已确认后不可再改）
const hasConfirmed = ref(false)
//判断答对是否自动跳转下一题
const if_click = ref(1)
const clearModel = ref(false)
const questionDrawer = ref(false)
// 判断显示隐藏解析
const if_analysis = ref(false)
const handleClose = () => {
  clearModel.value = false
}
const submitHandleClose = () => {
  submitModel.value = false
}


interface Question {
  questionId: string // 或 number
  title: string
  answer: string
  answered: string
  type: string
  img: string
  questionAnalysis: string
  isCorrect: number
  isCollected: number
  fastStudy: string
  options: any[]
  userAnswer: string
}

// console.log(currentQuestion, 'currentQuestion')
const tempAudio = ref()
const isplay = ref(false)
const audioMap = ref<any>({})
const audioUrl = ref('')

function stopAudio() {
  if (tempAudio.value) {
    tempAudio.value.pause()
    tempAudio.value = null
  }
  audioUrl.value = ''
  audioMap.value = {}
  isplay.value = false
}

watch(currentQuestionIndex, () => {
  stopAudio()
})

const getSpeechData = async () => {
  if (!currentQuestion.value) return
  const res = await getSpeechSynthesis({
    text: currentQuestion.value.title,
    volume: 0,
    speed: 0,
    voiceType: 0
  })
  if (res.code === '00000' && res.data && res.data.audio) {
    let base64 = res.data.audio
    let mimeType = 'audio/wav' // 默认类型
    // 检查base64头部信息
    if (typeof base64 === 'string') {
      // 处理带有data:前缀的base64
      const match = base64.match(/^data:(audio\/\w+);base64,(.*)$/)
      if (match) {
        mimeType = match[1]
        base64 = match[2]
      }
      // 解码base64为二进制
      const byteCharacters = atob(base64)
      const byteNumbers = new Array(byteCharacters.length)
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i)
      }
      const byteArray = new Uint8Array(byteNumbers)
      const blob = new Blob([byteArray], { type: mimeType })
      const tempUrl = URL.createObjectURL(blob)
      // 创建一个临时audio对象
      tempAudio.value = new Audio(tempUrl)
      tempAudio.value.onended = () => {
        isplay.value = false
      }
      tempAudio.value.onpause = () => {
        isplay.value = false
      }
      tempAudio.value.onplay = () => {
        isplay.value = true
      }
      tempAudio.value.play()
      audioUrl.value = tempUrl
      audioMap.value = { url: tempUrl }
    } else {
      return
    }
  }
}

const readQuestion = async () => {
  // 切题后，audioMap.value.url 已被清空，每次都重新获取语音
  if (isplay.value) {
    // 如果正在播放，则暂停
    if (tempAudio.value) {
      tempAudio.value.pause()
    }
    isplay.value = false
  } else {
    // 如果未播放，则开始播放
    isplay.value = true
    // 每次都重新获取语音，确保播放的是当前题内容
    await getSpeechData()
  }
}

const optionFun = (index: number, ele: any) => {
  // 多选(type=='0')：未确认前可切换
  if (currentQuestion.value?.type == '0') {
    if (hasConfirmed.value) return
    const pos = selectedOptions.value.indexOf(ele)
    if (pos > -1) {
      selectedOptions.value.splice(pos, 1)
    } else {
      selectedOptions.value.push(ele)
    }
    return
  }
  // 单选/判断：原逻辑
  if (!isSelect.value) {
    optionTab.value = index
    currentQuestion.value.answered = ele
    if (currentQuestion.value.answered == currentQuestion.value.answer && if_click.value == 1) {
      setTimeout(() => {
        nextQuestion()
      }, 100)
    } else if (currentQuestion.value.answered !== currentQuestion.value.answer) {
      // 选错了弹解析框
      if_analysis.value = true
      // 检查是否已存在该题，避免重复添加
      // const exists = wrongList.value.some(
      //   (item: any) => item.questionId === currentQuestion.value.questionId
      // )
      // if (!exists) {
      //   wrongList.value.push(currentOriginal.value)
      //   userStore.setWrongList(wrongList.value)
      // }
    }
  }
  isSelect.value = true
}

const checkAnswer = () => {
  let seleteValue = currentQuestion.value.answered
  if (seleteValue) {
    if (currentQuestion.value.type == '0') {
      const picked = seleteValue.split('').filter((ch: string) => /[A-D]/.test(ch))
      selectedOptions.value = picked
      const correct = currentQuestion.value.answer.split('')
      wrongSelectedOptions.value = picked.filter((op: any) => !correct.includes(op))
      hasConfirmed.value = true
      isSelect.value = true
    } else {
      currentQuestion.value.options.forEach((item: any, index: number) => {
        if (item.option == seleteValue) {
          optionTab.value = index
          isSelect.value = true
        }
      })
    }
  } else {
    optionTab.value = -1
    isSelect.value = false
    selectedOptions.value = []
    wrongSelectedOptions.value = []
    hasConfirmed.value = false
  }
}
const nextQuestion = () => {
  if (currentQuestionIndex.value < optionList.value.length - 1) {
    optionTab.value = -1
    isSelect.value = false
    selectedOptions.value = []
    wrongSelectedOptions.value = []
    hasConfirmed.value = false
    currentQuestionIndex.value++
    if_analysis.value = false
    checkAnswer()
    stopAudio()
  }
}
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
    optionTab.value = -1
    isSelect.value = false
    selectedOptions.value = []
    wrongSelectedOptions.value = []
    hasConfirmed.value = false
    checkAnswer()
    stopAudio()
  }
}
const upPull = () => {
  questionDrawer.value = !questionDrawer.value
}
const gotoQuestion = (index: number) => {
  currentQuestionIndex.value = index
  optionTab.value = -1
  selectedOptions.value = []
  wrongSelectedOptions.value = []
  hasConfirmed.value = false
  checkAnswer()
  stopAudio()
}
const clearRecord = () => {
  clearModel.value = true
}
const confrim = async () => {
  currentQuestionIndex.value = 0
  optionTab.value = -1
  isSelect.value = false
  const obj = {
    memberId: userStore.storeInfo.memberId,
    carModelId: userStore.storeInfo.carModelId,
    categoryId: userStore.categoryId,
    isSimulation: 1,
    answerRecords: [] as Array<{
      questionId: string
      userAnswer: string
      isCorrect: number
      isCollected: number
    }>,
    examId: examId.value
  }
  const answerSummary = optionList.value
    .filter((q) => q.answered)
    .map((q) => {
      return {
        questionId: q.questionId,
        userAnswer: '',
        isCorrect: q.answered === q.answer ? 1 : 0,
        isCollected: 0,
      }
    })
  obj.answerRecords = answerSummary
  try {
    const res = await getQuestionProgress(obj)
    if (res.code === '00000') {
      optionList.value
        .filter((q) => q.answered)
        .forEach((item) => {
          item.answered = ''
          item.isCollected = 0
        })
      ElMessage.success('答题清空成功')
    }
  } catch {
  } finally {
  }
  questionDrawer.value = false
  clearModel.value = false
}
const questionClose = () => {
  questionDrawer.value = false
}

const showBackToTop = ref(false)

const handleScroll = () => {
  const scrollContainer = document.querySelector('.analysis') || document.documentElement
  const scrollY = scrollContainer.scrollTop || window.scrollY
  showBackToTop.value = scrollY > 100 // 建议增大阈值
}

const scrollToTop = () => {
  const scrollContainer = document.querySelector('.analysis') || window
  scrollContainer.scrollTo({
    top: 0,
    behavior: 'smooth',
  })
}

const examId = ref('')
const getQuestionList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
  })
  try {
    let obj = {
      carModelId: userStore.storeInfo.carModelId,
      categoryId: userStore.categoryId,
      id: userStore.storeInfo.memberId,
      latestExamId: route.query.examId
    }
    const res = await getSimulateQuestion(obj)
    if (res.code === '00000' && res.data) {
      examId.value = res.data.examId
      originalTitle.value = res.data.wxQuestionS
      optionList.value = res.data.wxQuestionS.map((e: any) => {
        return {
          title: e.questionName,
          type: e.questionType,
          img: e.questionImg,
          options: [
            { option: 'A', name: e.questionA },
            { option: 'B', name: e.questionB },
            { option: 'C', name: e.questionC },
            { option: 'D', name: e.questionD },
          ],
          answer: e.answer,
          answered: '',
          fastStudy: e.fastStudy,
          questionAnalysis: e.questionAnalysis,
          questionId: e.id,
          isCorrect: e.isCorrect,
          isCollected: e.isCollected,
          originalIsCollected: e.isCollected
        }
      })
      const index = optionList.value?.reduce((lastIndex, current, currentIndex) => {
        return current.answered ? currentIndex : lastIndex
      }, -1)
      currentQuestionIndex.value = index == -1 ? 0 : index

      // 初始化当前题目的回显状态（兼容单选/判断/多选）
      if (currentQuestion.value) {
        checkAnswer()
      }
    }
  } finally {
    loading.close()
  }
}

const updateExamState = async () => {
  try {
    let obj = {
      memberId: userStore.storeInfo.memberId,
      examId: examId.value,
      status: 2,
      duration: totalSeconds.value // 使用剩余秒数而不是格式化的时间字符串
    }
    const res = await updateExamStatus(obj)
  } catch (error) {
  }
}
// 只保存用户本次操作过的数据（即本次进入页面后操作过的题目），之前做的数据不保存
const operatedQuestions = ref<Set<string>>(new Set())

// 在用户答题或收藏时调用此方法记录操作过的题目
const markQuestionOperated = (questionId: string) => {
  operatedQuestions.value.add(questionId)
}


const saveQuestionData = async (e: any) => {
  if (e) currentQuestion.value.isCollected = !currentQuestion.value.isCollected // e参数判断是否为收藏的时候保存数据

  if (!optionList.value || !optionList.value.length) return;

  markQuestionOperated(currentQuestion.value.questionId)
  const answerRecords: Array<{
    questionId: string
    userAnswer: string
    isCorrect: number
    isCollected: number
  }> = []

  optionList.value.forEach((q: any) => {
    // 只保存已作答的题目
    if (q.answered !== undefined && q.answered !== null && q.answered !== '') {
      let currentCollect
      if (q.originalIsCollected && !q.isCollected) {
        currentCollect = 2
      } else {
        currentCollect = q.isCollected ? 1 : 0
      }
      answerRecords.push({
        questionId: q.questionId,
        userAnswer: q.answered,
        isCorrect: q.answered === q.answer ? 1 : 0,
        isCollected: currentCollect,
      })
    }
  })

  console.log(answerRecords, "answerRecords===");

  if (answerRecords.length === 0) return
  const obj = {
    memberId: userStore.storeInfo.memberId,
    carModelId: userStore.storeInfo.carModelId,
    categoryId: userStore.categoryId,
    isSimulation: 1,
    answerRecords,
    status: 2,
    examId: examId.value
  }

  try {
    const res = await getQuestionProgress(obj)
    if (res.code === '00000' && !e) {
      // ElMessage.success('模拟考试记录保存成功')
    }
  } catch {
  } finally {
  }
}

const confirmMultipleChoice = () => {
  if (currentQuestion.value?.type != '0') return
  if (selectedOptions.value.length === 0) {
    ElMessage.warning('请至少选择一个选项')
    return
  }
  const picked = [...selectedOptions.value].sort()
  const correct = currentQuestion.value.answer.split('').sort()
  wrongSelectedOptions.value = picked.filter(op => !correct.includes(op))
  currentQuestion.value.answered = picked.join('')
  hasConfirmed.value = true
  // 全对自动跳题
  if (picked.join('') === correct.join('') && if_click.value == 1) {
    setTimeout(() => {
      nextQuestion()
    }, 100)
  } else {
    if_analysis.value = true
  }
}

const onSubmitEarly = async () => {
  // ElMessageBox.confirm('确定要提前交卷吗？', '确认', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'error',
  // }).then(() => {
  //   router.go(-1)
  // })
  // if (wrongState.value) {
  await saveQuestionData('')
  await updateExamState()
  // }
  submitModel.value = false
  questionModel.value = true
  // router.go(-1)
}

let timer: any = null

const formattedTime = computed(() => {
  const mins = Math.floor(totalSeconds.value / 60)
    .toString()
    .padStart(2, '0')
  const secs = (totalSeconds.value % 60).toString().padStart(2, '0')
  return `${mins}:${secs}`
})

const startTimer = () => {
  timer = window.setInterval(() => {
    // 如果已经显示了考试结果，则停止计时
    if (questionModel.value) {
      clearInterval(timer)
      return
    }
    if (totalSeconds.value > 0) {
      totalSeconds.value--
      const mins = Math.floor(totalSeconds.value / 60).toString().padStart(2, '0')
      const secs = (totalSeconds.value % 60).toString().padStart(2, '0')
      userStore.setShowTimer({
        formattedTime: `${mins}:${secs}`,
      })
    } else {
      clearInterval(timer)
      submitModel.value = true
      examSure.value = true //判断倒计时结束弹框
      // 这里可以触发自动交卷等逻辑
    }
  }, 1000)
}

const viewWrongQuestions = () => {
  if (wrongNum.value > 0) {
    console.log(optionList.value, 'optionList.value====');
    console.log(originalTitle.value, 'originalTitle.value====');
    wrongList.value = optionList.value
      .map((q, idx) => ({ q, idx }))
      .filter(({ q }) => q.answered && q.answered !== q.answer)
      .map(({ idx }) => originalTitle.value[idx])
    userStore.setWrongList(wrongList.value)
    questionModel.value = false
    // router.push({ path: '/mnExam', query: { wrong: 1 } })
    router.push({ path: 'wrongCheck' })
  } else {
    ElMessage.success('暂无错题')
  }
}

// const getWrongList = () => {
//   optionList.value = userStore.wrongList.map((e: any) => {
//     return {
//       title: e.questionName,
//       type: e.questionType,
//       img: e.questionImg,
//       options: [
//         { option: 'A', name: e.questionA },
//         { option: 'B', name: e.questionB },
//         { option: 'C', name: e.questionC },
//         { option: 'D', name: e.questionD },
//       ],
//       answer: e.answer,
//       answered: e.userAnswer,
//       fastStudy: e.fastStudy,
//       questionAnalysis: e.questionAnalysis,
//       questionId: e.id,
//       isCorrect: e.isCorrect,
//       isCollected: e.isCollected,
//       originalIsCollected: e.isCollected
//     }
//   })
//   const index = optionList.value?.reduce((lastIndex, current, currentIndex) => {
//     return current.answered ? currentIndex : lastIndex
//   }, -1)
//   currentQuestionIndex.value = index == -1 ? 0 : index

//   currentQuestion.value?.options.forEach((item: any, index: number) => {
//     if (item.option == currentQuestion.value.answered) {
//       item.option == currentQuestion.value.answered) {
//         optionTab.value = index
//         isSelect.value = true
//       }
//     }
//   })
// }
const backToQuestionBank = () => { router.go(-1) }
onMounted(async () => {
  console.log(12312312);

  const scrollContainer = document.querySelector('.analysis') || window
  scrollContainer.addEventListener('scroll', handleScroll)
  handleScroll() // 初始检查
  await getQuestionList()
  startTimer()
  userStore.setShowTimer({ showTimer: true })
})

onUnmounted(async () => {
  const scrollContainer = document.querySelector('.analysis') || window
  scrollContainer.removeEventListener('scroll', handleScroll)
  // await saveQuestionData('')
  // await updateExamState()
  clearInterval(timer)
  userStore.setShowTimer({ showTimer: false })
  stopAudio()
})
</script>
<style scoped lang="scss">
@use './order.scss' as *;

:deep(.question-drawer) {
  .el-drawer {
    height: rem(900) !important;
  }

  .el-drawer__body {
    height: 100%;
    // overflow: hidden;
    padding: 0;
  }
}

:deep(.transparent-drawer-overlay) {
  background-color: transparent !important;
}
</style>
